﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LevenBlog.Core.Install {
    public class InstallOperationCollection : List<IInstallOperation> {
        public EventHandler<InstallRunningArgs> ExecuteOperation { get; set; }

        public IInstallOperation Current { get; protected set; }

        public int Finished { get; protected set; }

        public virtual void OnRunning(InstallRunningArgs e) {
            if (ExecuteOperation != null) {
                ExecuteOperation(this, e);
            }
        }

        public virtual void OnRuned(InstallRunningArgs e) {
            if (ExecuteOperation != null) {
                ExecuteOperation(this, e);
            }
        }

        public virtual void Run() {
            Finished = 0;
            OperationContext context = new OperationContext();
            foreach (var item in this) {
                Current = item;
                OnRunning(new InstallRunningArgs(Current, Count, Finished));
                var r = item.Execute(context);
                if (!r.Result) {
                    throw new InstallException(r.Errors.ToErrorString(), Current);
                }
                Finished++;
                OnRuned(new InstallRunningArgs(Current, Count, Finished));
            }
        }
    }
}
